package com.github.rxyor.common.support.aspect.crypto;

import com.github.rxyor.common.core.exception.AuthenticationException;
import com.github.rxyor.common.support.util.CryptoUtil;
import com.github.rxyor.common.support.util.HttpServletUtil;
import javax.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 *<p>
 * 加密接口拦截切面
 *</p>
 *
 * @author liuyang
 * @date 2019/11/7 周四 16:36:00
 * @since 1.0.0
 */
@SuppressWarnings("all")
@Slf4j
@AllArgsConstructor
public class CryptoApiResolver {

    private final HttpServletRequest request;

    public Object processJoinPoint(ProceedingJoinPoint point) throws Throwable {
        String sign = getSign();
        boolean verifyResult = false;
        if (StringUtils.isNotBlank(sign)) {
            try {
                verifyResult = CryptoUtil.verify(sign);
            } catch (Exception e) {
                log.error("解密出错:{}", e);
            }
        }
        if (Boolean.TRUE.equals(verifyResult)) {
            return point.proceed();
        }
        log.warn("无权访问, ip:{}, path:{}, sign:{}, methodName:{}", HttpServletUtil.parseIpFromRequest(request),
            request.getRequestURI(), sign, point.getSignature().getName());
        throw new AuthenticationException("您无权访问该接口");
    }

    /**
     * 取sign签名的值
     *
     * @return
     */
    private String getSign() {
        String sign = request.getParameter(CryptoUtil.REQUEST_PARAM_CONST_KEY);
        if (StringUtils.isBlank(sign)) {
            sign = request.getHeader(CryptoUtil.REQUEST_PARAM_CONST_KEY);
        }
        return sign;
    }

}
